/**
 * BLANK IMAGE URL
 * @type String
 */
Ext.BLANK_IMAGE_URL = './extjs/resources/images/default/s.gif';

Menu = {};

/**
 * 用户菜单Panel
 */
MenuPanel = function() {
	
    MenuPanel.superclass.constructor.call(this, {
        id:'menu-tree',
        region:'west',
        split:true,
        header: false,
        width: 215,
        minSize: 215,
        maxSize: 300,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        animCollapse:false,
        animate: false,
        collapseMode:'mini',
        /*loader: new Ext.tree.TreeLoader({
			preloadChildren: true,
			clearOnLoad: false
		}),
        root: new Ext.tree.AsyncTreeNode({
            text:'功能菜单',
            id:'root',
            expanded:true,
            children:[Menu.treeData]
     	}),*/
        loader: new Ext.tree.TreeLoader({
    		dataUrl: 'functions/module_list.do',
    		requestMethod: 'GET'
    	}),
    	root: new Ext.tree.AsyncTreeNode({
    		id: 'root', 
    		text: '功能菜单',  
    		expanded:true
    	}),
        collapseFirst:false
    });
};

/**
 * 扩展MenuPanel
 * @class MenuPanel
 * @extends Ext.tree.TreePanel
 */
Ext.extend(MenuPanel, Ext.tree.TreePanel, {
	
    initComponent: function(){
        
        this.hiddenPkgs = [];
        
        Ext.apply(this, {
        	tbar:[ 
	        	' ',
				new Ext.form.TextField({
					width: 150,
					emptyText:'菜单检索...',
	                enableKeyEvents: true,
					listeners:{
						render: function(f){
	                    	/*this.filter = new Ext.tree.TreeFilter(this, {
	                    		clearBlank: true,
	                    		autoClear: true
	                    	});*/
							this.filter = new QM.ux.TreeFilter(this, {
								clearAction: 'expand'
							}); 
						},
						keyup: {
			                fn:function(t, e){
			                  	this.filter.filter(t.getValue());
			                },
			                buffer: 350,
			                scope: this
			            },
	                   /*keydown: {
	                        fn: this.filterTree,
	                        buffer: 350,
	                        scope: this
	                    },*/
	                    scope: this
					}
				}), 
				' ', ' ',
				{
	                iconCls: 'icon-expand-all',
					tooltip: '展开全部',
	                handler: function(){ this.root.expand(true); },
	                scope: this
	            }, 
	            '-', 
	            {
	                iconCls: 'icon-collapse-all',
	                tooltip: '折叠全部',
	                handler: function(){ this.root.collapse(true); },
	                scope: this
            	}
            ]
        });
        MenuPanel.superclass.initComponent.call(this);
    },
    
    /**
     * 菜单树过滤
     * @param {} t
     * @param {} e
     */
	filterTree: function(t, e){
		var text = t.getValue();
		Ext.each(this.hiddenPkgs, function(n){
			n.ui.show();
		});
		if(!text){
			this.filter.clear();
			return;
		}
		this.expandAll();
		
		var re = new RegExp('^' + Ext.escapeRe(text), 'i');
		this.filter.filterBy(function(n){
			return !n.attributes.isClass || re.test(n.text);
		});
		
		// 将没有过滤出来的空节点隐藏
		this.hiddenPkgs = [];
        var me = this;
		this.root.cascade(function(n){
			if(!n.attributes.isClass && n.ui.ctNode.offsetHeight < 3){
				n.ui.hide();
				me.hiddenPkgs.push(n);
			}
		});
	},
	
	/**
	 * 再激活tabpanel的时候选中对应的树节点
	 * @param {} cls
	 */
    selectClass : function(cls){
        if(cls){
            var parts = cls.toString().split('.');
            var last = parts.length-1;
            var res = [];
            var pkg = [];
            for(var i = 0; i < last; i++){ // things get nasty - static classes can have .
                var p = parts[i];
                var fc = p.charAt(0);
                var staticCls = fc.toUpperCase() == fc;
                if(p == 'Ext' || !staticCls){
                    pkg.push(p);
                    res[i] = 'pkg-'+pkg.join('.');
                }else if(staticCls){
                    --last;
                    res.splice(i, 1);
                }
            }
            res[last] = cls;

            this.selectPath('/root/menu/'+res.join('/'));
        }
    }
});

/**
 * 工作面板
 * @class WorkPanel
 * @extends Ext.Panel
 */
WorkPanel = Ext.extend(Ext.Panel, {
    closable: true,
	layout: 'fit',
    autoScroll:true,
    actionMapping: '',
    
    initComponent : function(){

    	/*Ext.apply(this,
        	{
	            tbar: [
		            '->',
		            {
		                text: '相关选项',
		                handler: function(){alert("相关选项")},
		                iconCls: 'icon-config'
		            }, 
		            '-',
		            {
		                text: '页面帮助',
		                handler: this.showHelpMsg,
		                scope: this,
		                iconCls: 'icon-fav'
		            }, 
		            '-', 
		            {
					 	tooltip: '滚动到页面顶部',
						handler:this.scrollToTop,
						scope:this,
						iconCls:'icon-scrolltop'
				 	}
			 	]
        	}
        );*/
        
    	// eg: "/node/modulelist.do"
        var className = this.getClassNameFromHref(this.actionMapping);
        eval("var content = new " + className + "();");
        // content只能作为设置为 center
/*
        Ext.apply(content, {
            region: 'center'
        });
*/
        this.items = [content];
        
        WorkPanel.superclass.initComponent.call(this);
    },

    /**
     * 页面帮助
     */
    showHelpMsg : function() {
        Ext.Msg.alert('页面帮助 - ' + this.cclass, "此页面显示功能的简述信息");
    },
    
    /**
     * 滚动到页面最顶部
     */
	scrollToTop: function() {
		this.body.scrollTo('top',0,true);
	},

	/**
	 * 映射js函数名
	 * */
	getClassNameFromHref: function(url) {
        var className = "Ext.master";
        var endIndex = url.lastIndexOf(".");
        var classNameWithUrl = url.substring(0, endIndex);
        if(url.indexOf(0) == '/'){
            classNameWithUrl = url.substring(1, endIndex);
        }
        var classNameArray = classNameWithUrl.split("/");
        for(var i=0; i<classNameArray.length; i++) {
        	var subName = classNameArray[i].replace(/(^\s*)|(\s*$)/g, "");
        	if(subName != "") {
                if(i == classNameArray.length -1) {
                    subName = subName.charAt(0).toUpperCase() + subName.substring(1);
                }
        		className += "." + subName;
            }
        }
		return className;
	}
});

/**
 * 工作空间
 */
MainPanel = function(){
	
    MainPanel.superclass.constructor.call(this, {
        id:'doc-body',
        region:'center',
        margins:'0 5 5 0',
        resizeTabs: true,
        minTabWidth: 135,
        tabWidth: 135,
        plugins: new Ext.ux.TabCloseMenu(),
        enableTabScroll: true,
        activeTab: 0,

        items: {
            id:'workbench-panel',
            title: '我的工作台',
            //autoLoad: {url: 'welcome.html', callback: function(){}, scope: this},
            iconCls:'icon-docs',
            autoScroll: true
        }
    });
};

Ext.extend(MainPanel, Ext.TabPanel, {
	
	loadPanel : function(url, nodeId, text, member){
        var id = 'taskpanel-' + nodeId;
        var tab = this.getComponent(id);
        if(tab) {
            this.setActiveTab(tab);
        }else {
            var autoLoad = {url: url};
            var p = this.add(new WorkPanel(
            	{
	                id: id,
	                title: text,
	                cclass: nodeId,
	                //iconCls: Menu.icons[nodeId],
	                //autoLoad: autoLoad,
	                actionMapping: url 
            	}
            ));
            this.setActiveTab(p);
        }
    }
});

/**
 * 页面初始化
 */
Ext.onReady(function(){

    Ext.QuickTips.init();

    var menu = new MenuPanel();
    var mainPanel = new MainPanel();

    menu.on('click', function(node, e){
         if(node.isLeaf()){
            e.stopEvent();
            mainPanel.loadPanel(node.attributes.url, node.id, node.text);
         }
    });
	
	// scroll position saver on tab-change
    mainPanel.on('tabchange', function(tp, tab){
        menu.selectClass(tab.cclass);
		if (this.tabScrolls[tab.cclass]) {
			var scrollElement=tab.getEl().child('.x-panel-body');
			if (scrollElement) {
				scrollElement.scrollTo('top',this.tabScrolls[tab.cclass].top);	
			}
		}
		 
    },mainPanel);
	
	mainPanel.on('beforetabchange',function(tp,newtab,oldtab) {
		if (typeof this.tabScrolls=='undefined') this.tabScrolls={};
		if (oldtab) {
			var scrollElement=oldtab.getEl().child('.x-panel-body');
			if (scrollElement) {
				this.tabScrolls[oldtab.cclass] = scrollElement.getScroll();	
			}
			
		}
	},mainPanel);
	
	var tbarPanel = new Ext.Panel({
        border: false,
        bodyStyle: 'width:100%',
        layout: 'anchor',
        region: 'north',
        cls: 'docs-header',
        height: 26,
        items: [{
            xtype: 'box',
            //el: 'header',
            border: false,
            anchor: 'none -28'
        },
        new Ext.Toolbar({
            id: 'head_toolbar',
            cls: 'top-toolbar',
            items: [' ', ' ', ' ',
            {
                iconCls: 'icon-expand-all',
                tooltip: '隐藏菜单',
                text: '隐藏菜单',
                handler: function () {
                }
            }, '-',
            
            '->', '-',
            {
                iconCls: 'icon-collapse-all',
                tooltip: '关闭所有页签',
                text: '关闭所有页签',
                handler: function () {
                }
            }]
        })]
    });
    
    var workspacePanel = new Ext.Panel(
		{
			layout: 'border',
			region: 'center',
			items:[
		       	tbarPanel,
		       	menu,
		       	mainPanel
			]
		}
    );
    
    var viewport = new Ext.Viewport(
    	{
	        layout:'border',
	        items:[ 
	        	{
		            cls: 'docs-header',
		            height: 30,
		            region:'north',
		            xtype:'box',
		            el:'header',
		            border:false,
		            margins: '0 0 5 0'
	        	}, 
	        	workspacePanel 
	        ]
    	}
    );
	
    // 展开到指定目录层级
    menu.expandPath('/root/menu');

    // 初始化我的工作台
    var workbenchTabpanel = Ext.getCmp('workbench-panel');
    var workbench = new WorkbenchPanel();
    workbenchTabpanel.add(workbench);
    workbench.init();
    
    // 重新布局
    viewport.doLayout();
	
	setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({remove:true});
    }, 250);
	
});